/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

因为是树的结构，一般都是用递归来实现。  树的特别结构决定了该数据结构特别适合用递归



 */
class Solution {
public:
    TreeNode* rebuild(vector<int>& pre, int pre_left, int pre_right, vector<int>& vin, int vin_left, int vin_right) {
        if (pre_left > pre_right || vin_left>vin_right) return nullptr;
 
        TreeNode* root = new TreeNode(pre[pre_left]);
        for (int i=vin_left; i<=vin_right; ++i) {
            if (vin[i] == root->val) {                                                                                   //注意这里前序数组的边界问题，传pre_left+1 
                root->left = rebuild(pre, pre_left+1, pre_left+i-vin_left, vin, vin_left, i-1);                        //是因为pre_left是当前根节点，数组的右边界应当是
                root->right = rebuild(pre, pre_left+i-vin_left+1, pre_right, vin, i+1, vin_right);                     //pre_left+中序左子树的长度 即(i-1-vin_left+1)
                break;                                                                                                 // pre_left+i-1-vin_left+1=pre_left+i-vin_left
            }                                                                                                          //第二个rebuild的边界是第一个rebuild数组边界+1  因为根是数组的第一个位置，后面全是子数组
        }
        return root;
    }
    
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        return rebuild(pre, 0, pre.size()-1, vin, 0, vin.size()-1);

    }
};





/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */



class Solution {
public:

    TreeNode* rebuild(vector<int> & pre,int preLeft,int preRight,vector<int> &mid,int midLeft,int midRight)
    {
        if(preLeft>preRight || midLeft>midRight)
        {
            return nullptr;
        }
        
        TreeNode *CurrRoot=new TreeNode(pre[preLeft]);
        for(int i=midLeft;i<=midRight;++i)
        {
            if(mid[i]==CurrRoot->val)   ///这里的逗号要去掉
            {

                CurrRoot->left=rebuild(pre,preLeft+1,preLeft+i-midLeft ,mid,midLeft,i-1);
                CurrRoot->right=rebuild(pre,preLeft+i-midLeft+1,preRight ,mid,i+1,midRight);
                break;  ///注意这里的break
            }
            
        }
        return CurrRoot;

    }
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        
        
       return rebuild(pre,0,pre.size()-1,vin,0,vin.size()-1);
        

    }
};

